package com.example.acountingappliaction;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.acountingappliaction.DBHelper;
import com.google.android.material.textfield.TextInputEditText;

public class Login_activity extends AppCompatActivity {

    private TextInputEditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvGoRegister;
    private DBHelper dbHelper;
    private Animation scaleInAnim;
    // 记录当前输入是否存在错误
    private boolean isUsernameError = false;
    private boolean isPasswordError = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化动画
        scaleInAnim = AnimationUtils.loadAnimation(this, R.anim.scale_in);

        // 初始化数据库
        dbHelper = new DBHelper(this);

        // 初始化控件
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvGoRegister = findViewById(R.id.tv_go_register);

        // 设置输入监听
        setupTextWatchers();

        // 按钮点击动画
        btnLogin.setOnClickListener(v -> {
            v.startAnimation(scaleInAnim);
            login();
        });

        // 注册跳转
        tvGoRegister.setOnClickListener(v -> {
            v.startAnimation(scaleInAnim);
            startActivity(new Intent(Login_activity.this, Register_activity.class));
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });
    }

    /**
     * 设置输入框文本变化监听器
     */
    private void setupTextWatchers() {
        // 用户名输入监听
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当用户输入变化且之前有错误时，检查是否已输入正确的用户名
                if (isUsernameError) {
                    String input = s.toString().trim();
                    if (!input.isEmpty() && dbHelper.isUsernameExists(input)) {
                        // 用户名正确，恢复正常状态
                        resetEditTextState(etUsername);
                        isUsernameError = false;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 密码输入监听
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当用户输入变化且之前有错误时，检查密码是否正确（需要结合用户名）
                if (isPasswordError) {
                    String username = etUsername.getText().toString().trim();
                    String password = s.toString().trim();
                    if (!username.isEmpty() && !password.isEmpty()
                            && dbHelper.verifyPassword(username, password)) {
                        // 密码正确，恢复正常状态
                        resetEditTextState(etPassword);
                        isPasswordError = false;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void login() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 重置错误状态
        resetAllErrors();

        // 输入验证
        if (username.isEmpty()) {
            showError(etUsername, "请输入用户名", true);
            return;
        }

        if (password.isEmpty()) {
            showError(etPassword, "请输入密码", true);
            return;
        }

        // 检查用户名是否存在
        if (!dbHelper.isUsernameExists(username)) {
            showError(etUsername, "用户名不存在", true);
            Toast.makeText(this, "用户名不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查密码是否正确
        if (!dbHelper.verifyPassword(username, password)) {
            showError(etPassword, "密码错误", true);
            Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
            return;
        }

        // 登录成功
        Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
        startActivity(new Intent(this, MainActivity.class));
        finish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }

    /**
     * 显示错误状态
     * @param editText 输入框
     * @param message 错误信息
     * @param isError 是否标记为错误状态
     */
    private void showError(EditText editText, String message, boolean isError) {
        editText.setError(message);
        editText.requestFocus();
        editText.startAnimation(AnimationUtils.loadAnimation(this, R.anim.shake));
        // 设置输入框背景为红色（需要在drawable中创建error_bg.xml）
        editText.setBackgroundResource(R.drawable.error_bg);

        // 更新错误状态标记
        if (editText == etUsername) {
            isUsernameError = isError;
        } else if (editText == etPassword) {
            isPasswordError = isError;
        }
    }

    /**
     * 重置输入框状态为正常
     */
    private void resetEditTextState(EditText editText) {
        editText.setError(null);
        // 恢复默认背景（使用你原来的输入框背景）
        editText.setBackgroundResource(R.drawable.default_edittext_bg);
    }

    /**
     * 重置所有错误状态
     */
    private void resetAllErrors() {
        if (isUsernameError) {
            resetEditTextState(etUsername);
            isUsernameError = false;
        }
        if (isPasswordError) {
            resetEditTextState(etPassword);
            isPasswordError = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }
}